var TBody = Backbone.View.extend({
	tagName: "tbody",
	initialize: function() {
		this.render();
		this.model.on("change", this.render, this);
	},
	render: function() {
		var html = _.template($("#rows_template").html(), this.model.toJSON());
		// if(this.model.get('data').length > 0){
		this.body = $(html);
		this.$el.html(this.body);
		var t = this;
		var module = this.options.blockName;
		$('tr', this.$el).click(function() {
			if (!$(this).hasClass('selected')) {
				$('.selected', $(this).parent()).removeClass('selected');
				$(this).addClass('selected');
			}
		}).dblclick(function() {
			$(this).click();
			var model = false;
			ViewData[module].val = $('td', this).eq(ViewData[module].sort[0]).text();
			if (ViewData[module].tabs.length > 0) model = ViewData[module].tabs.find(function(tab) {
				return tab.get('item') && tab.get('item').val == ViewData[module].val; //ViewData[module].search.val
			})

			if (!model) {
				var obj = {
					item: {
						val: ViewData[module].val
					}
				}
				model = ViewData[module].tabs.add(obj).last();
			}
			

			var type = module.toLowerCase();
			$.ajax({
				url: util.sfbase + "/rest/" + type + "/get",
				type: "POST",
				dataType: "json",
				data: {
					ndaid: $(this).attr('ndaid')
				},
				error: function(xhr, ajaxOptions, thrownError) {
					//$.unblockUI();
					alert("error:" + thrownError);
					return false;
				},
				success: function(data) {
					if (data.flag == 0) {

						//construct page
						var page_readOnly = true;
						// viewFactory[module+"DetailBlock"]().$el.append(t.$el.parent());
						var g = PT.groupArray[module.toUpperCase()];
						if (g.flag) {
							g.obj.setValue(data);
						} else {
							func.constructPage(page_readOnly, PT.getRootUricPage(type), viewFactory[module + "DetailBlock"](), data);
						}
						model.set('subName', module.toUpperCase() );
						model.set('data', data);
						model.view.$el.click();
					}
				}
			});


		});


	}

});

var Table = Backbone.View.extend({
	initialize: function() {
		this.render();
		this.model.on("change:data", this.buildTable, this);
	},

	render: function() {
		var data = this.model.get('data');
		if (data.length == 0) return;
		var html = _.template($("#table_template").html(), this.options.head, {
			variable: "headers"
		});
		this.table = $(html);
		this.$el.html(this.table);
		this.heads = $('thead th', this.table);

		this.sortEvents();
		// this.dataModel = new ItemModel(this.model.get('data'));
		// this.empty = $('tbody tr', this.table);
		this.bodyModel = new ItemModel({
			data: [
				[]
			]
		});
		this.blockName = this.model.get('block');
		this.body = new TBody({
			el: $('tbody', this.table),
			empty: this.empty,
			model: this.bodyModel,
			blockName: this.blockName
		});


		// if(this.blockName){
		// this.table.width(util.getBlock(this.blockName).width());
		// }
		// this.table.flextable({
		// resizeableClass: 'resizeable',
		// ghostClass: 'ghost',
		// ellipsisClass: 'truncate',
		// resizeTableWidthOnColResize: true
		// });
		this.table.colResizable({
			liveDrag: true
		})

		this.buildPager(data);
	},

	buildTable: function() {
		if ($("thead th", this.$el).length == 0) this.render();
		else {
			this.buildPager(this.model.get('data'));
			this.sortEvents();
		}
	},
	sortEvents: function() {
		var t = this;
		var data = this.model.get('data');
		var block = this.model.get('block');
		for (var i = 0; i < ViewData[block].sort.length; i++) {
			var n = ViewData[block].sort[i];
			this.heads.eq(n)
			.attr('class','sort')
			.html(this.heads.eq(n).text()+"<i class='icon-resize-vertical'></i>")
			.click(function() {
				var index = $(this).attr('i') - 0 + 1;
				if($(this).hasClass('active')){
					if($(this).hasClass('up')){ // to down
						$(this).removeClass('up').addClass('down');
						$(this).children('i').attr('class','icon-arrow-down');
						t.buildPager(_.sortBy(data, function(arr) {
							return arr[index].toUpperCase();
						}).reverse());
					}
					else if($(this).hasClass('down')){ // to original
						$(this).removeClass('down');
						$(this).children('i').attr('class','icon-resize-vertical');
						t.buildPager(data);
					}
					else{
						$(this).addClass('up');
						$(this).children('i').attr('class','icon-arrow-up');
						t.buildPager(_.sortBy(data, function(arr) {
							return arr[index].toUpperCase();
						}));
					}
				}
				else{
					$(this).parent().children('.active').attr('class','sort')
					.children(i).attr('class','icon-resize-vertical');
					$(this).addClass('active up');
					$(this).children('i').attr('class','icon-arrow-up');
					t.buildPager(_.sortBy(data, function(arr) {
						console.log(index);
						return arr[index].toUpperCase();
					}));				
				}

			})
			// .toggle(function() {
			// 	var index = $(this).index();
			// 	t.buildPager(_.sortBy(data, function(arr) {
			// 		return arr[n].toUpperCase();
			// 	}));
			// 	$(this).parent().children('.active').attr('class','sort')
			// 	.children(i).attr('class','icon-resize-vertical');
			// 	$(this).addClass('acitve up');
			// 	$(this).children(i).attr('class','icon-arrow-up');
			// }, function() {
			// 	t.buildPager(_.sortBy(data, function(arr) {
			// 		return arr[n].toUpperCase();
			// 	}).reverse());
			// 	$(this).removeClass('up').addClass('down');
			// 	$(this).children(i).attr('class','icon-arrow-down');
			// }, function() {
			// 	t.buildPager(data);
			// 	$(this).css({
			// 		"color": "black"
			// 	});
			// 	$(this).removeClass('down');
			// 	$(this).children(i).attr('class','icon-resize-vertical');
			// });
		}
	},
	buildPager: function(data) {
		if (this.pager) this.pager.remove();
		this.pager = $("<div></div>")
		this.$el.append(this.pager);

		this.pager.pagination(data.length, {
			items_per_page: 5,
			num_edge_entries: 2,
			num_display_entries: 5,
			load_first_page: true,
			callback: this.pageCallback,
			data: data,
			model: this.bodyModel
		});
	},
	pageCallback: function(cur, root) {
		// if(root.parent().length ==0 )
		// return false;
		var p = this.items_per_page,
			start = cur * p,
			end = Math.min((cur + 1) * p, this.count),
			data = this.data.slice(start, end);
		this.model.set('data', data);
		return false;
	}
});